// pages/scan/scan.js
const app = getApp()

Page({
  data: {
    scanResult: null,
    scanning: false
  },

  onLoad() {
    // 页面加载时的初始化
  },

  // 扫码
  scanCode() {
    const that = this
    this.setData({
      scanning: true
    })

    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res)
        that.handleScanResult(res.result)
      },
      fail: (err) => {
        console.error('扫码失败:', err)
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        })
        that.setData({
          scanning: false
        })
      }
    })
  },

  // 处理扫码结果
  handleScanResult(qrCode) {
    app.request({
      url: '/scanReport',
      method: 'POST',
      data: {
        qr_code: qrCode
      }
    }).then((res) => {
      this.setData({
        scanResult: res.data,
        scanning: false
      })
      
      // 显示扫码成功提示
      wx.showToast({
        title: '扫码成功',
        icon: 'success'
      })
    }).catch((err) => {
      console.error('扫码报工失败:', err)
      this.setData({
        scanning: false
      })
      wx.showToast({
        title: err.msg || '扫码失败',
        icon: 'none'
      })
    })
  },

  // 跳转到报工页面
  goToReport() {
    if (this.data.scanResult) {
      wx.navigateTo({
        url: `/pages/report/report?allocation_id=${this.data.scanResult.id}`
      })
    }
  },

  // 重新扫码
  rescan() {
    this.setData({
      scanResult: null
    })
    this.scanCode()
  }
}) 